import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '../../store'
import { Checkbox, ProductCard, Stepper, SubmitBar, Dialog } from 'react-vant'
import './style.css'
import { CarItemState, chnageCarItemCreateAction, switchCarItemCheckCreateAction, changeSwitchAllCreateAction, deleteCarItem } from '../../store/car/car'
const Index = () => {
	const car = useSelector((state: RootState) => state.carReducer.car)
	const dispatch = useDispatch()

	const changeCar = (count: number | string, id: number) => {
		dispatch(chnageCarItemCreateAction({ id, count: +count }))
	}

	const switchCar = (id: number) => {
		dispatch(switchCarItemCheckCreateAction({ id }))
	}

	const changeAllChcked = (checked: boolean) => {
		dispatch(changeSwitchAllCreateAction(checked))
	}

	const deleteCar = (id: number) => {
		Dialog.confirm({
			title: '警告',
			message: '再减少就要删除了！！！',
		}).then(() => {
			dispatch(deleteCarItem(id));
		}).catch(() => {

		})
	}	

	const computedPrice = () => {
		return car.reduce((p, n) => {
			return n.isCheck ?  p + n.price * n.count : p
		}, 0) * 100
	}

	return (
		<div>
			<div>	{
				car.map(v => {
					return (
						<div className='item' key={v.id}>
							<div className='item-check'>
								<Checkbox checked={v.isCheck} onChange={() => switchCar(v.id)}></Checkbox>
							</div>
							<div className='item-card'>
								<ProductCard
									price={v.price.toFixed(2)}
									desc={<div className="rv-ellipsis">{v.desc}</div>}
									title={v.title}
									thumb={v.url}
									num={
										<Stepper 
											value={v.count} 
											onChange={(value) => changeCar(value, v.id)}
											onOverlimit={ () => deleteCar(v.id) }
										></Stepper>
									}
								/>
							</div>
						</div>
					)
				})
			}</div>

			<SubmitBar
				price={ computedPrice() }
				buttonText="提交订单"
			>
				<Checkbox checked={ car.every(v => v.isCheck) } onChange={ 
						(checked) => {
							changeAllChcked(checked)
						} }>全选</Checkbox>
			</SubmitBar>
		</div>
	)
}


export default Index